package com.design.graduation.asdemo.network;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.design.graduation.asdemo.utils.LogUtils;
import com.design.graduation.asdemo.utils.ToastUtil;


import java.io.IOException;

import com.design.graduation.asdemo.network.model.ApiError;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * @author by weijianxing on 10/13/15.
 */
public abstract class AsyncCallBack<T> implements Callback<T> {


    @Override
    public void onResponse(Response<T> response, Retrofit retrofit) {
        if (response.isSuccess()) {
            success(response.body());
        } else {
            try {
                error(response.errorBody().string());
            }  catch (JSONException jsonException) {
                jsonException.printStackTrace();

                ToastUtil.showShortToast("服务器开小差了，稍后再试...");
            } catch (IOException ioException){
                ioException.printStackTrace();
            } catch(Exception exception) {
                exception.printStackTrace();
                throw exception;
            }
        }
    }

    public abstract void success(T result);

    public void error(String json) {
        LogUtils.e(json);
        ApiError apiError = JSON.parseObject(json, ApiError.class);
        System.out.println("登录错误");
        ToastUtil.showShortToast(apiError.getMessage());
    }

    @Override
    public void onFailure(Throwable t) {
        LogUtils.d(t);
    }
}
